<template>
  <!-- mode="vertical" -->
  <a-menu
    v-model:selectedKeys="state.selectedKeys"
    :open-keys="state.openKeys"
    mode="inline"
    @openChange="(e: any) => onOpenChange(e as string[])"
    @click="handleClick"
  >
    <menus :routes="routes" :select="state.selectedKeys" />
  </a-menu>
</template>
<script lang="ts" setup>
import { MenuProps } from 'ant-design-vue';
import { RouteLocationNormalizedLoaded, RouteRecordRaw, useRoute, useRouter } from 'vue-router';
const router = useRouter();
const route = useRoute();

const props = defineProps<{ routes: Array<RouteRecordRaw> }>();

const state = reactive<{ [key: string]: string[] }>({
  openKeys: [],
  rootSubmenuKeys: [],
  selectedKeys: [],
});
const onOpenChange = (openKeys: string[]) => {
  const latestOpenKey = openKeys.find(key => state.openKeys.indexOf(key) === -1);
  if (state.rootSubmenuKeys.indexOf(latestOpenKey!) === -1) {
    state.openKeys = openKeys;
  } else {
    state.openKeys = latestOpenKey ? [latestOpenKey] : [];
  }
};
const handleClick: MenuProps['onClick'] = menuInfo => {
  state.selectedKeys = [menuInfo.key.toString()];
  console.log(menuInfo)
  router.push({ path: menuInfo.key.toString() });
};

const fillRoute = (route: Array<RouteRecordRaw>) => {
  route.forEach(r => {
    if (r.meta && r.meta.menu_show) {
      state.rootSubmenuKeys.push(r.path);
    }
    if (r.children && r.children.length > 0) {
      fillRoute(r.children);
    }
  });
};
const dynamic_route = (r: RouteLocationNormalizedLoaded) => {
  if (state.rootSubmenuKeys && state.rootSubmenuKeys.length > 0) {
    // state.openKeys = [r.path];
    state.selectedKeys = [r.path];
    state.openKeys = [];
    state.rootSubmenuKeys.forEach(submenu => {
      if (r.path.indexOf(submenu) > -1 && r.path !== submenu) {
        state.openKeys.push(submenu);
      }
    });
  }
};
watch(route, newVal => {
  dynamic_route(newVal);
});

watch(
  () => props.routes,
  newVal => {
    fillRoute(newVal);
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  // fillRoute(props.routes);
  dynamic_route(route);
});
</script>
<style lang="scss" scoped></style>
